package org.dawing.shop.cart.rest;

import org.axonframework.commandhandling.gateway.CommandGateway;
import org.dawing.shop.cart.application.CartAppService;
import org.dawning.shop.common.commands.cart.AddToCartCommand;
import org.dawning.shop.common.commands.cart.CreateCartCommand;
import org.dawning.shop.common.domain.cart.CartId;
import org.dawning.shop.common.domain.cart.CartProduct;
import org.dawning.shop.common.vo.CategoryAttribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by miou on 2017/6/14 0014.
 */
@RestController
@RequestMapping("cart")
public class CartDomainController {

    @Autowired
    private CartAppService cartAppService;

    @Autowired
    private CommandGateway commandGateway;

    /** 检查商品库存*/
    @RequestMapping("/{id}")
    public void test(@PathVariable String id){
        cartAppService.checkProductStock(id);
    }

    /** 向用户购物车内添加商品*/
    @RequestMapping("/add/{userId}/{shopId}/{projectId}")
    public void add(@PathVariable String userId, @PathVariable String shopId,
                    @PathVariable String projectId, @RequestBody List<CategoryAttribute> attributes){
        CartId id = new CartId(userId);
        CartProduct cartProduct = new CartProduct();
        cartProduct.setShopId(shopId);
        cartProduct.setProductId(projectId);
        cartProduct.setAttributes(attributes);
        cartProduct.setPrice(new BigDecimal(100));
        cartProduct.setQuantity(1);
        String sku = cartAppService.getSku(cartProduct);
        commandGateway.send(new AddToCartCommand(id,cartProduct,sku));
    }

    /** 创建用户购物车*/
    @RequestMapping("/create/{userId}")
    public void create(@PathVariable String userId){
        CartId id = new CartId(userId);
        CartProduct cartProduct = new CartProduct();
        if(cartProduct!=null){
            if(cartProduct.getShopId() ==null || cartProduct.getShopId().equals("")){
                cartProduct.setShopId("yunjing");
            }
            if(cartProduct.getQuantity()<0){
                cartProduct.setQuantity(0);
            }
        }
        String sku = cartAppService.getSku(cartProduct);
        commandGateway.send(new CreateCartCommand(id,cartProduct,sku));
    }

}
